package com.aiyige.page.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.ExRouter;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.request.ScanQRRequest;
import com.aiyige.model.request.WebLoginRequest;
import com.aiyige.model.response.ScanResponse;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Route;

import io.github.xudaojie.qrcodelib.CaptureActivity;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * xiachao 2018、6、6
 */
@Route(path = ARouterConfig.ScanQRCodePage, extras = ARouterConfig.EXTRA_NEED_BINDPHONE | ARouterConfig.EXTRA_NEED_LOGIN)
public class ScanQRcodePage extends CaptureActivity {
    protected Activity mActivity = this;

    private AlertDialog mDialog;

    private boolean waittingResponse = false;//等待返回

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mActivity = this;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void handleResult(String resultString) {
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(mActivity, io.github.xudaojie.qrcodelib.R.string.scan_failed, Toast.LENGTH_SHORT).show();
            restartPreview();
        } else {
//            if (mDialog == null) {
//                mDialog = new AlertDialog.Builder(mActivity)
//                        .setMessage(resultString)
//                        .setPositiveButton("确定", null)
//                        .create();
//                mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                    @Override
//                    public void onDismiss(DialogInterface dialog) {
//                        restartPreview();
//                    }
//                });
//            }
//            if (!mDialog.isShowing()) {
//                mDialog.setMessage(resultString);
//                mDialog.show();
//            }
            requestLogin(resultString);
        }
    }

    private void requestLogin(final String resultString) {

        if (TextUtils.isEmpty(resultString) || waittingResponse) {
            return;
        }
        if (resultString.contains("webkey=")) {
            String webkey = "";
            try {
                String result[] = resultString.split("webkey=");
                webkey = result[1];
            } catch (Exception e) {
                finish();
            }
            waittingResponse = true;
            WebLoginRequest.newBuilder().scanQRRequest(ScanQRRequest.newBuilder().webkey(webkey).build()).build().enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    waittingResponse = false;
                    if (response != null) {
                        if (response.isSuccessful()) {
                            try {
                                ScanResponse scanResponse = JsonUtil.toObject(response.body().string(), ScanResponse.class);
                                if (scanResponse != null && scanResponse.getCode() == 201) {
                                    ToastX.show(getString(R.string.login_success));
                                    finish();
                                } else {
                                    onFailure(call, null);
                                }
                            } catch (Exception e) {
                                onFailure(call, e);
                            }
                        } else {
                            ErrorUtil.handleErrorResponse(response, true);
                            handler.sendEmptyMessageDelayed(0, 2000);
                        }
                    } else {
                        onFailure(call, null);
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    waittingResponse = false;
                    ToastX.show(getString(R.string.login_failed_please_retry));
                    handler.sendEmptyMessageDelayed(0, 2000);
                }
            });
        } else if (resultString.startsWith("http")) {
            if (resultString.contains(BuildConfig.PRIMARY_DOMAIN) && (/*resultString.contains(ExRouter.HOME) || */resultString.contains(ExRouter.PHOTO_DETAIL) || resultString.contains(ExRouter.VIDEO_DETAIL) || resultString.contains(ExRouter.VIDEO_COURSE_DETAIL))) {
                String router = "";
                try {
                    if (resultString.startsWith("http")) {
                        router = BuildConfig.AIYIGE_APP_SCHEME + resultString.substring(4);
                    } else if (resultString.startsWith("https")) {
                        router = BuildConfig.AIYIGE_APP_SCHEME + resultString.substring(5);
                    }
                } catch (Exception e) {

                }
                Router.start(router);
                finish();

            } else if (resultString.contains(BuildConfig.PRIMARY_DOMAIN)) {// 个人主页跳转浏览器外链
//                if (resultString.contains("home")) {
//                    Uri uri = Uri.parse(resultString);
//                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                    startActivity(intent);
//                    finish();
//                } else {
//                    Router.start(resultString);
//                    finish();
//                }
                Router.start(resultString);
                finish();
            } else {
                new android.support.v7.app.AlertDialog.Builder(this).setTitle(R.string.open_url_hint).setMessage(resultString)
                        .setPositiveButton(R.string.open_url, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Uri uri = Uri.parse(resultString);
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                                dialog.dismiss();
                                finish();

                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();
            }

        } else {
            new android.support.v7.app.AlertDialog.Builder(this).setTitle(R.string.scan_result).setMessage(resultString)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();

                        }
                    }).show();

        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            restartPreview();
        }
    };

}
